<template>
    <div class="">
        <el-form :inline="true">
            <div style="display: flex; justify-content: space-between;">
                <div>
                    <el-form-item>
                        <el-input v-model="key" clearable placeholder="请输入查询内容" style="width: 200px;" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="init">查询</el-button>
                    </el-form-item>
                </div>
                <div>
                    <el-button type="primary" @click="onVisible(1)">新增</el-button>
                </div>
            </div>
        </el-form>
        <el-table v-loading="listLoading" :data="tableData" border style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" align="center" />
            <el-table-column prop="picurl" label="logo" width="90" align="center">
                <template slot-scope="{row}">
                    <el-image style="width: 50px; height: 50px" :src="row.picurl.split(',')[0]"
                        :preview-src-list="row.picurl.split(',')" />
                </template>
            </el-table-column>
            <el-table-column prop="shopname" label="名称" align="center" />
            <el-table-column prop="content" label="店铺描述" align="center" />
            <el-table-column prop="username" label="结算用户" align="center" />
            <!-- <el-table-column prop="ccount" label="收藏人数" width="80" align="center" /> -->
            <el-table-column prop="shoptype" label="类型" align="center">
                <template slot-scope="{row}">
                    <el-tag v-if="row.shoptype == 1" type="danger">线上</el-tag>
                    <el-tag v-if="row.shoptype == 2">线下</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="ctime" label="创建时间" align="center" />
            <el-table-column label="操作" width="200" align="center">
                <template slot-scope="{row}">
                    <el-button size="mini" type="primary" @click="onVisible(2, row)">编辑</el-button>
                    <!-- <el-button size="mini" type="primary" v-if="row.state == 1"
                        @click="$router.push({ name: 'storeData', query: { userid: row.userid } })">店铺数据</el-button> -->
                </template>
            </el-table-column>
        </el-table>
        <div class="block " style="padding-top: 20px;">
            <el-pagination background :current-page="PageIndex" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="totalCount"
                @size-change="idx => { pageSize = idx }" @current-change="idx => { PageIndex = idx }" />
        </div>

        <!-- 新增、编辑 -->
        <el-dialog width="1000px" :close-on-click-modal="false" :title="visibleType == 1 ? '新增' : '编辑'"
            :visible.sync="dialogVisible" @open="openDialog('forms')" @closed="closedDialog">
            <el-form id="forms" ref="forms" :rules="rulesModel" :model="form" label-width="100px"
                style="max-height: 600px;overflow-y: scroll;">
                <div>
                    <el-form-item label="店铺logo" prop="picurl">
                        <UploadImageList :isImageList="false" :existImage="headImage" @success="val => headImage = val"
                            :isDisplay="dialogVisible" />
                    </el-form-item>
                </div>
                <div>
                </div>
                <el-form-item label="店铺名称" prop="shopname" style="width: 900px">
                    <el-input v-model="form.shopname" type="text" placeholder="请输入店铺名称" />
                </el-form-item>
                <el-form-item label="店铺描述" prop="content" style="width: 900px">
                    <el-input v-model="form.content" type="textarea" placeholder="请输入店铺描述" />
                </el-form-item>
                <el-form-item label="结算用户" prop="username">
                    <div class="flex">
                        <el-input v-model="form.username" type="text" :disabled="true" style="width: 150px"
                            placeholder="请选择用户" />
                        <el-button style="margin-left: 20px;" type="primary" @click="select(1)">请选择</el-button>
                    </div>
                </el-form-item>
                <!-- <el-form-item label="管理用户" prop="sysusername">
                    <el-select v-model="form.sysusername" filterable placeholder="请选择" @change="selectChange">
                        <el-option :key="0" label="请选择" :value="0"></el-option>
                        <el-option v-for="item in sysUserList" :key="item.id" :label="item.username" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="线上/线下" prop="shoptype">
                    <el-switch v-model="form.shoptype" :active-value="1" :inactive-value="2" />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button :loading="buttonLoading" type="primary" @click="onEdit(1)">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 选择用户对话框 -->
        <el-dialog title="选择用户" :visible.sync="dialogUser" width="1000px" :close-on-click-modal="false">
            <div style="height: 500px;overflow: scroll;" @closed="handleUserListClose">
                <el-form :inline="true">
                    <div style="display: flex; justify-content: space-between;">
                        <div>
                            <el-form-item label="账号">
                                <el-input v-model="usernameKey" clearable placeholder="请输入账号" style="width: 200px;" />
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="getUserList">查询</el-button>
                            </el-form-item>
                        </div>
                        <div />
                    </div>
                </el-form>
                <el-table v-loading="userLoading" :data="userList" border style="width: 100%">
                    <el-table-column prop="userid" label="ID" width="60" align="center" />
                    <el-table-column prop="headpicurl" label="头像" width="80" align="center">
                        <template slot-scope="scope">
                            <el-avatar size="large" :src="scope.row.headpicurl" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="username" label="账号" align="center" />
                    <el-table-column prop="nickname" label="昵称" align="center" />
                    <el-table-column prop="isv" label="姓名" width="100" align="center">
                        <template slot-scope="{row}">
                            <el-tag v-if="row.isv == 0" type="danger">未认证</el-tag>
                            <span v-if="row.isv == 1">{{ row.truename }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="phone" label="手机号" align="center" />
                    <el-table-column label="操作" width="80" align="center">
                        <template slot-scope="{row}">
                            <el-button size="mini" type="primary" @click="selectClick(row)">选择</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-dialog>

    </div>
</template>
  
<script>
import { MallShopPage, mallshopEdit, MallShopInfo, SetMallState } from '@/api/goods'
import { userlist } from '@/api/users.js'
import { GetPage_SysUsers } from '@/api/sys.js'
import editor from "../../../components/Editor/index.vue"; // 富文本组件
import { formatDate } from '@/utils/index.js'
export default {
    name: 'Name',
    components: { editor },
    data() {
        return {
            // 筛选参数
            key: '', // 关键字查询

            // 列表
            listLoading: false,// 列表加载中
            tableData: [],
            totalCount: 0,
            PageIndex: 1,
            pageSize: 10,

            // 审核对话框
            dialogVisible1: false,
            buttonLoading1: false, // 按钮加载中
            form1: {}, // 详情实体
            rulesModel1: {
                state: [
                    { required: true, message: '请选择审核状态', trigger: 'blur' }
                ],
                content: [
                    { required: true, message: '请输输入驳回原因', trigger: 'blur' }
                ],
            },


            // 新增\编辑对话框
            dialogVisible: false,
            buttonLoading: false, // 按钮加载中
            visibleType: "", // 1:新增；2：编辑
            form: {}, // 详情实体
            rulesModel: {
                picurl: [
                    { required: true, message: '请上传店铺logo', trigger: 'blur' }
                ],
                shopname: [
                    { required: true, message: '请输入店铺名称', trigger: 'blur' }
                ],
                content: [
                    { required: true, message: '请输入店铺描述', trigger: 'blur' }
                ],
                username: [
                    { required: true, message: '请选择结算用户', trigger: 'blur' }
                ],
                sysusername: [
                    { required: true, message: '请选择管理用户', trigger: 'blur' }
                ],
                shoptype: [
                    { required: true, message: '请选择店铺类型', trigger: 'blur' }
                ],
            },

            headImage: '',


            // 选择用户对话框相关
            dialogUser: false,
            userLoading: false, // 用户列表加载中
            usernameKey: '', // 账号筛选
            userList: [], // 用户列表
            isUserType: 1, // 1: 结算用户；2：管理员用户

            sysUserList: [], // 系统用户列表
        }
    },
    watch: {
        PageIndex(val) {
            console.log(val)
            this.getData()
        },
        pageSize(val) {
            console.log(val)
            this.getData()
        }
    },
    created() {

    },
    async mounted() {
        this.getData()
    },
    methods: {
        /////////////////////////////////////////////////// 初始化 ////////////////////////////////////////////////
        /**列表初始化 */
        async init() {
            this.PageIndex = 1;
            this.getData();
        },
        /**表单参数初始化 */
        initForm() {
            this.form = {
                id: 0,
                shopname: '', // 店铺名称
                content: '', // 店铺描述
                picurl: '', // 店铺logo
                userid: 0, // 结算用户
                username: '', // 结算用户名
                ccount: 0, // 收藏人数
                sysuserid: 0, // 管理员用户id
                sysusername: '', // 管理用户名
                shoptype: 1, // 店铺类型
                password: '0', // 初始密码
                createaccount: 0, // 是否已创建账号
                state: 1, // 0：待审核；1审核通过；2：驳回

                backcontent: '0', // 驳回原因
                license: '0', // 营业执照
                doorpicurl: '0', // 门头照
            };
        },
        /////////////////////////////////////////////////// 弹窗 ////////////////////////////////////////////////////

        /////////////////////// 主对话框  ///////////////////////
        /**
         * 对话框打开前
         * @param {*} form_id 表单id
         */
        openDialog(form_id) {
            // 滚动条移动到表单顶部
            this.$nextTick(() => {
                document.getElementById(form_id).scrollTop = 0;
            });
        },
        /**
         * 新增/编辑按钮点击
         * @param {*} type 1：新增；2：编辑
         * @param {*} info 操作数据对象
         */
        async onVisible(type, info = {}) {
            this.visibleType = type;
            this.initForm();

            // 编辑
            if (type === 2) {
                // 获取详情
                const { data } = await MallShopInfo({
                    shopid: info.id
                });
                this.form = { ...data };
                this.headImage = this.form.picurl;
            }

            // 获取用户列表
            this.getUserList();

            // 获取系统用户列表
            this.getSysUserList();

            this.dialogVisible = true;
        },
        /**对话框关闭结束（新增\编辑） */
        closedDialog() {
            // 清空上传组件图片
            this.headImage = '';
            // 移除表单项的校验结果
            this.$refs.forms.clearValidate();
        },
        /////////////////////// 选择用户对话框  ///////////////////////
        /**打开前（选择用户对话框） */
        select(type) {
            this.isUserType = type;
            this.dialogUser = true;
        },
        /**点击选择按钮（选择用户操作） */
        selectClick(item) {
            if (this.isUserType == 1) {
                this.form.userid = item.userid;
                this.form.username = item.username;
            } else {
                this.form.sysuserid = item.userid;
                this.form.sysusername = item.username;
            }
            this.dialogUser = false;
        },
        /**关闭前（选择用户对话框） */
        handleUserListClose() {
            this.usernameKey = '';
        },
        /////////////////////// 审核对话框  ///////////////////////
        onVisible1(row) {
            // 先初始化
            this.form1 = {
                currentId: row.id,
                state: '',
                content: ''
            }

            this.dialogVisible1 = true
        },
        /**对话框关闭结束（审核） */
        closedDialog1() {
            // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
            this.$refs.form1.resetFields()
            // 移除表单项的校验结果
            this.$refs.form1.clearValidate();
            this.dialogVisible1 = false;
        },
        /**
         * 选择审核状态回调
         * @param {*} e 目前的选中值
         */
        selectState(e) {
            this.form1.content = '';
            this.form1.sysuserid = 0;
            this.form1.sysusername = '';
        },
        /**
         * 选中系统用户回调
         * @param {*} e 目前的选中值
         */
        selectChange(e) {
            this.sysUserList.forEach(item => {
                if (item.id == e) {
                    this.form.sysuserid = item.id;
                    this.form.sysusername = item.username;
                }
            });
        },
        /////////////////////////////////////////////////// 数据请求 ////////////////////////////////////////////////
        /**获取主列表 */
        async getData() {
            this.listLoading = true
            const { list, totalCount, success, msg } = await MallShopPage({
                key: this.key,
                PageIndex: this.PageIndex,
                PageSize: this.pageSize
            })
            this.totalCount = totalCount
            if (list) {
                this.tableData = [];
                list.forEach(element => {
                    element.ctime = element.ctime.replace('T', ' ')
                    element.utime = element.utime.replace('T', ' ')
                    this.tableData.push(element)
                })
            }
            this.listLoading = false
        },
        /**审核提交 */
        async submit() {
            // 表单校验
            try {
                await this.$refs['form1'].validate()
            } catch (e) {
                console.log(e)
                return
            }
            this.form1.state = Number(this.form1.state) || 0;
            this.form1.content = this.form1.content || '0';
            this.buttonLoading1 = true
            try {
                const { success, msg } = await SetMallState({
                    state: this.form1.state,
                    content: this.form1.content
                }, [this.form1.currentId]);
                this.buttonLoading1 = false
                if (success) {
                    this.dialogVisible1 = false
                    this.getData()
                }
                this.$message({
                    message: msg,
                    type: success ? 'success' : 'error'
                })
            } catch (error) {
                this.buttonLoading1 = false
            }
        },
        /**确定提交（新增/编辑） */
        onEdit() {

            this.form.picurl = this.headImage;

            // 表单校验
            this.$refs['forms'].validate(async (valid) => {
                if (valid) {
                    this.form.state = Number(this.form.state) || 0
                    this.form.password = this.form.password || '0'

                    this.buttonLoading = true
                    try {
                        const { success, msg } = await mallshopEdit(this.form)
                        this.buttonLoading = false
                        if (success) {
                            this.dialogVisible = false
                            this.getData()
                        }
                        this.$message({
                            message: msg,
                            type: success ? 'success' : 'error'
                        })
                    } catch (error) {
                        this.buttonLoading = false
                    }

                } else {
                    return false
                }
            })
        },
        /**获取用户列表 */
        async getUserList() {
            this.userLoading = true
            const { list, pageIndex, totalCount } = await userlist({
                key: this.usernameKey,
                PageIndex: 1,
                PageSize: 10
            })
            this.userLoading = false
            if (list) {
                this.userList = [];
                list.forEach(element => {
                    element.createtime = element.createtime.replace('T', ' ')
                    element.lastlogintime = element.lastlogintime.replace('T', ' ')
                    this.userList.push(element)
                })
            }
        },
        /**获取系统用户列表 */
        async getSysUserList() {
            const { list, pageIndex, totalCount } = await GetPage_SysUsers({
                PageIndex: 1,
                PageSize: 10
            })
            this.sysUserList = list
        },
    }
}
</script>
  
<style lang="scss" scoped></style>
<style lang="scss">
.el-table .warning-row {
    background: oldlace;
}

// 上传图片相关样式
.avatar-uploader .el-upload {
    width: 178px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
</style>
  